from django.contrib.auth.models import User
from django.db import models

# Create your models here.
from utils.modelsMixin import ModelSetMixin, DateTimeModelMixin


class Label(DateTimeModelMixin):
    name = models.CharField(max_length=30, verbose_name="标签名", unique=True)

    def __str__(self):
        return self.name


class Article(ModelSetMixin):
    STATUS_CHOICES = ((0, "未发布"), (1, "发布"))
    title = models.CharField(max_length=100, verbose_name="标题")
    digest = models.CharField(max_length=300, verbose_name="摘要")
    content = models.TextField(verbose_name="文章内容")
    page_view = models.IntegerField(verbose_name="浏览量", default=0)
    priority = models.IntegerField(verbose_name="优先级", default=0)
    status = models.IntegerField(verbose_name="状态", default=0, choices=STATUS_CHOICES)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    label = models.ForeignKey(Label, on_delete=models.CASCADE)

    def __str__(self):
        return "标题：%s，作则：%s" % (self.title, self.user.username)

    class Meta:
        # 排序 按照先后顺序来进行比较，先看优先级，再看浏览量，再看创建时间
        ordering = ["-priority", "-page_view", "-create_time"]


class Comment(ModelSetMixin):
    content = models.TextField(verbose_name="评论的内容")
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    # 管理器：源模型类名小写_set comment_set
    # 外键可以关联自身，对自身的主键进行关联
    # related_name 通过管理器查询就是反向查询 定义反向引用名称
    # parent_comment_set 访问到当前模型的实例
    # 管理器重命名related_name
    parent_comment = models.ForeignKey('self', verbose_name="父级评论id", null=True, blank=True, on_delete=models.CASCADE,
                                       related_name='parent_comment_set')
    replay_comment = models.ForeignKey('self', verbose_name="回复评论", null=True, blank=True, on_delete=models.CASCADE,
                                       related_name='reply_comment_set')

    class Meta:
        ordering = ['-create_time']

    def __str__(self):
        return "%s:%s"%(self.user.username,self.content)